﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static ATEGo.CmdField;

namespace ATEGo
{
    //———————————————————————【回显分析】————————————————————————
    public partial class Executor
    {
        /// <summary>
        /// 分析回显：发送一条命令的回显可能多次发送回来，每次都会触发该事件
        /// </summary>
        /// <param name="thisTime_echo"></param>
        private void AnalysisEcho(string thisTime_echo)
        {
            //向缓冲区中增加log
            Running_Cmd_Buffer.AppendLine(thisTime_echo);
            //本次增加的回显为空，不需要分析; 不接收回显也不需要分析
            if (string.IsNullOrWhiteSpace(thisTime_echo) || !IsReceiveEcho)
            {
                return;
            }
            //将多次累加的回显进行分析
            string all_echo = Running_Cmd_Buffer.ToString();
            if (Running_Cmd != null)
            {
                //1.匹配结束回显
                //分析缓冲区是否满足结束正则，满足则分析其他正则
                var matches = Regex.Matches(all_echo, Running_Cmd[finishReg]);
                if (matches.Count > 0)
                {
                    if (IsPrintDebugInfo)
                    {
                        WriteFlow_Content("1.匹配到结束回显。");
                    }
                    //由于回显的限制，可能需要多次匹配到结束回显
                    if (matches.Count >= Running_Cmd[finishRegTimes].JsonToInt32())
                    {
                        if (IsPrintDebugInfo)
                        {
                            WriteFlow_Content($"1.匹配到结束回显第{Running_Cmd[finishRegTimes]}次。进入分析...");
                        }
                        IsReceiveEcho = false;
                        //判定结束回显
                        var finalResult = Analysis_FinishReg_Result(all_echo);
                        //执行下一条命令
                        Running_TCS.TrySetResult(finalResult);
                        return;
                    }
                }

                //2.匹配到失败正则【忽略失败匹配】
                if (!string.IsNullOrWhiteSpace(Running_Cmd[failReg]))
                {
                    if (!AnalysisFailReg(all_echo, "2."))
                    {
                        IsReceiveEcho = false;
                        Running_TCS.TrySetResult(false);
                        return;
                    }
                }
                //3.匹配到成功正则【忽略失败匹配】
                if (!string.IsNullOrWhiteSpace(Running_Cmd[successReg]))
                {
                    if (AnalysisSuccessReg(all_echo, "3."))
                    {
                        IsReceiveEcho = false;
                        Running_TCS.TrySetResult(true);
                        return;
                    }
                }
                //4.匹配到抓取正则【忽略失败匹配】
                if (!string.IsNullOrWhiteSpace(Running_Cmd[grabReg]))
                {
                    if (AnalysisGrabReg(all_echo, "4.", false))
                    {
                        IsReceiveEcho = false;
                        Running_TCS.TrySetResult(true);
                        return;
                    }
                }
                //5.匹配到下一条命令ifReg正则【忽略失败匹配】
                if (Next_Cmd != null && !string.IsNullOrWhiteSpace(Next_Cmd[ifReg]))
                {
                    if (Regex.IsMatch(all_echo, Next_Cmd[ifReg]))
                    {
                        WriteFlow_Success("匹配到下一条命令的ifReg");
                        IsReceiveEcho = false;
                        Running_TCS.TrySetResult(true);
                        return;
                    }
                }
            }
        }
        /// <summary>
        /// 分析结束回显后的结果【正视失败匹配】
        /// </summary>
        /// <param name="result"></param>
        private bool Analysis_FinishReg_Result(string echo)
        {
            //1.2 匹配到失败正则
            if (!string.IsNullOrWhiteSpace(Running_Cmd[failReg]))
            {
                var result = AnalysisFailReg(echo, "1.2");
                if (!result)
                {
                    return false;
                }
            }
            //1.3 匹配到成功正则
            if (!string.IsNullOrWhiteSpace(Running_Cmd[successReg]))
            {
                return AnalysisSuccessReg(echo, "1.3");
            }
            //1.4 匹配到抓取正则，放入抓取字段中
            if (!string.IsNullOrWhiteSpace(Running_Cmd[grabReg]))
            {
                return AnalysisGrabReg(echo, "1.4", true);
            }
            //1.1 所有情况不匹配
            return WriteFlow_Fail(@"1.1 failReg\succeessReg\grabReg均为空");
        }
        /// <summary>
        /// 分析失败回显，返回false为匹配到失败回显
        /// </summary>
        /// <param name="echo"></param>
        /// <returns></returns>
        private bool AnalysisFailReg(string echo, string sn)
        {
            string reg = Running_Cmd[failReg].Trim().ReplaceParas(this,true);
            if (Regex.IsMatch(echo, reg))
            {
                return WriteFlow_Fail($"{sn}匹配到failReg");
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 分析成功回显，返回true为匹配到成功回显
        /// </summary>
        /// <param name="echo"></param>
        /// <returns></returns>
        private bool AnalysisSuccessReg(string echo, string sn)
        {
            string reg = Running_Cmd[successReg].Trim().ReplaceParas(this,true);
            if (Regex.IsMatch(echo, reg))
            {
                return WriteFlow_Success($"{sn}匹配到successReg");
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 分析抓取正则
        /// </summary>
        /// <param name="echo"></param>
        /// <param name="isIgnoreFail"></param>
        /// <returns></returns>
        private bool AnalysisGrabReg(string echo, string sn, bool isConfrontFail = true)
        {
            string reg = Running_Cmd[grabReg].Trim().ReplaceParas(this, true);
            MatchCollection match = Regex.Matches(echo, reg);
            //匹配到东西
            if (match.Count >= 1)
            {
                //是否需要循环匹配所有的匹配项
                bool isALL = (Running_Cmd[grabRegTimes].Trim().ToLower() == "all");
                int matchIndex = 0;
                //不需要所有的话，获取到第几个匹配项
                if (!isALL)
                {
                    //判断索引
                    int index = Running_Cmd[grabRegTimes].JsonToInt32() - 1;
                    //检查
                    if (index < 0 || index >= match.Count)
                    {
                        if (IsPrintDebugInfo)
                        {
                            WriteFlow_Content($"{sn}grabRegTimes设置的值{Running_Cmd[grabRegTimes]}超过了匹配到的数目{match.Count}");
                        }
                        return false;
                    }
                    //获取到第几个匹配项
                    matchIndex = index;
                }
                //循环
                for (; matchIndex < match.Count; matchIndex++)
                {
                    //最后一次循环，视为不是isALL，好使用下面的跳出循环部分
                    if (matchIndex == match.Count - 1)
                    {
                        isALL = false;
                    }
                    Match onceMatch = match[matchIndex];
                    //放入抓取结果
                    WriteFlow_Content($"{sn}匹配到grabReg，抓取值为: ");
                    WriteFlow($"{onceMatch.Value}");
                    //将捕获组的值放入默认变量$1，到下一条命令就会失效；如果有多个匹配项，则只有最后一个匹配项有效
                    for (int i = 0; i < onceMatch.Groups.Count; i++)
                    {
                        Params_GrabResult[$"${i}"] = onceMatch.Groups[i].Value;
                    }
                    //将捕获组的值放入命令变量中，长久存放。以供后面命令使用。
                    //每个组放入一个变量中，从组1开始
                    if (!string.IsNullOrWhiteSpace(Running_Cmd[grabParams]))
                    {
                        var outparams = Running_Cmd[grabParams].Trim().Split(',');
                        for (int i = 0; i < outparams.Length; i++)
                        {
                            if (i + 1 < onceMatch.Groups.Count)
                            {
                                Params_InCmd[outparams[i]] = onceMatch.Groups[i + 1].Value;
                                if (IsPrintDebugInfo)
                                {
                                    WriteFlow_Content($"{sn}令{outparams[i]} = {onceMatch.Groups[i + 1].Value}");
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    //1.3.1 grabStd标准值进行比较
                    if (!string.IsNullOrWhiteSpace(Running_Cmd[grabStd]) && onceMatch.Groups.Count >= 1)
                    {
                        //判断Group的索引
                        int stdGroup_Index = Running_Cmd[grabStdGroup].JsonToInt32();
                        if (stdGroup_Index < 0 || stdGroup_Index >= onceMatch.Groups.Count)
                        {
                            if (IsPrintDebugInfo)
                            {
                                WriteFlow_Content($"{sn}grabStdGroup设置的值{Running_Cmd[grabStdGroup]}超过了捕获组的数目{onceMatch.Groups.Count}");
                            }
                            return false;
                        }
                        //抓取值
                        var stdValue = onceMatch.Groups[stdGroup_Index].Value;
                        WriteFlow_Content($"{sn}1 抓取第{stdGroup_Index}组值为：{stdValue}");
                        //直接#PASS#
                        if (CmdIsPass(Running_Cmd[grabStd].Trim()))
                        {
                            return WriteFlow_Success($"{sn}1 要求PASS");
                        }
                        //标准值,替换命令中变量
                        var stdCmds = Running_Cmd[grabStd].Trim().ReplaceParas(this).Split('|','&');
                        var msg = "";
                        // 不等于1并且不等于2
                        if(Running_Cmd[grabStd].Trim().StartsWith("!=")|| Running_Cmd[grabStd].Trim().StartsWith("<>"))
                        {
                            for(int i = 0; i< stdCmds.Length;i++)
                            {
                                var std = stdCmds[i].Trim();
                                //以不等号开头，表示不等于
                                if (std.StartsWith("!=") || std.StartsWith("<>"))
                                {
                                    std = std.Replace("!=", "").Replace("<>", "");
                                    if (std != stdValue)//一次匹配则继续
                                    {
                                        //只有最后一个才返回，其他则继续
                                        if (i==stdCmds.Length-1)
                                        {
                                            return WriteFlow_Success($"{sn}1 匹配到grabStd≠{stdValue}");
                                        }
                                    }
                                    else//一次不匹配则跳出
                                    {
                                        msg = $"{sn}1 匹配不到grabStd≠{stdValue}";
                                        break;
                                    }
                                }
                            }
                        }
                        // 等于1或等于2
                        else
                        {
                            foreach (var temp in stdCmds)
                            {
                                var std = temp.Trim();
                                if (std.StartsWith("=="))
                                {
                                    std = std.Replace("==", "");
                                }
                                if (std == stdValue)//一次匹配到则跳出
                                {
                                    return WriteFlow_Success($"{sn}1 匹配到grabStd={stdValue}");
                                }
                                else//一次不匹配则继续
                                {
                                    msg = $"{sn}1 匹配不到grabStd={stdValue}";
                                }
                            }
                        }
                        //不是ALL匹配的话，则跳出循环，上面没有匹配到，报失败
                        if (!isALL)
                        {
                            if (isConfrontFail)
                            {
                                return WriteFlow_Fail(msg);
                            }
                            return false;
                        }
                        //是ALL匹配的话，继续匹配
                        else
                        {
                            continue;
                        }
                    }
                    //1.3.2 grabJudge语句比较
                    if (!string.IsNullOrWhiteSpace(Running_Cmd[grabJudge]))
                    {
                        //替换命令中变量
                        var judgeCmd = Running_Cmd[grabJudge].Trim().ReplaceParas(this);
                        //执行语句
                        var t = CSharpExecute.EvalExpression(judgeCmd);
                        //执行结果
                        if (Convert.ToBoolean(t))
                        {
                            return WriteFlow_Success($"{sn}2 grabJudge为{t}，{judgeCmd}");
                        }
                        else
                        {
                            if (!isALL)
                            {
                                if (isConfrontFail)
                                {
                                    return WriteFlow_Fail($"{sn}2 grabJudge为{t}，{judgeCmd}");
                                }
                                return false;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    //1.3.3（上面两个必须为空）
                    return WriteFlow_Success($"{sn}3 抓取grabReg成功");
                }
            }
            //匹配不到东西并且需要正视错误
            if (isConfrontFail)
            {
                return WriteFlow_Fail($"{sn}匹配不到grabReg");
            }
            return false;
        }
    }
}
